import { useState, useEffect, useMemo, useRef } from 'react'
import { resourcePath } from '../../../../../../../utils/resource';
import { Button, Table } from 'antd';
import useBusinessMap from '../../../../../../common/BusinessMap/useBusinessMap';
import { createLayer, navByWkt, wktToFeature } from '../../../../../../../utils/helper/mapHelper';
import JcyjApi from '../../../../../../../utils/apis/JcyjApi';
import BlockTitle from '../../../../../../framework/BlockTitle';
import BlockBody from '../../../../../../framework/BlockBody';
import { Icon, Style } from 'ol/style';
import useMap from '../../hooks/useMap';
import BlockPanel from '../../common/BlockPanel';
import ScrollTable from '../../../../../../common/ScrollTable';
import { SearchOutlined } from '@ant-design/icons';
export default function BasicTable(props) {
    const { jcdlx, title, mapIcon, mapScale } = props;
    const [datas, setDatas] = useState();
    const map = useMap();
    const [scrollingPaused, setScrollingPaused] = useState(false);
    const [currentPage, setCurrentPage] = useState(1);
    const tableRef = useRef();
    const scrollTimerRef = useRef(null);
    const tableBodyRef = useRef(null);

    const layer = useMemo(() => {
        return createLayer((feature) => {
            return new Style({
                image: new Icon({
                    src: mapIcon,
                    scale: mapScale || 0.7,
                    anchor: [0.5, 1]
                })
            })
        }, [], {
            zIndex: 99
        });
    }, [mapIcon, mapScale]);

    useEffect(() => {
        if (layer && datas) {
            map.dispatchEvent({
                type: 'legend-layer',
                layer,
                icon: mapIcon,
                title
            });
            const features = datas?.filter(data => {
                return data.geom
            }).map(data => {
                const f = wktToFeature(data.geom)
                f.setProperties({ ...data });
                return f;
            })
            layer.getSource().addFeatures(features)
            layer.set('visible', false)
            map.addLayer(layer);
        }
    }, [layer, map, mapIcon, title, datas])

    useEffect(() => {
        JcyjApi.jcdList({
            jcdlx
        }).then(resp => {
            setDatas(resp.rows)
        });
    }, [jcdlx])

    // useEffect(() => {
    //     const scrollTableBody = () => {
    //         if (scrollingPaused || !tableBodyRef.current) return;

    //         // 获取表格body的DOM元素
    //         const tableBody = tableBodyRef.current.querySelector('.ant-table-body');
    //         if (!tableBody) return;

    //         const scrollHeight = tableBody.scrollHeight;
    //         const scrollTop = tableBody.scrollTop;
    //         const clientHeight = tableBody.clientHeight;

    //         // 如果已经滚到底部，回到顶部
    //         if (scrollTop + clientHeight >= scrollHeight) {
    //             tableBody.scrollTop = 0;
    //         } else {
    //             // 每次滚动1像素
    //             tableBody.scrollTop += 1;
    //         }
    //     };

    //     // 清除之前的定时器
    //     if (scrollTimerRef.current) {
    //         clearInterval(scrollTimerRef.current);
    //     }

    //     // 设置新的定时器，每50毫秒滚动一次，实现平滑滚动效果
    //     scrollTimerRef.current = setInterval(scrollTableBody, 50);

    //     return () => {
    //         if (scrollTimerRef.current) {
    //             clearInterval(scrollTimerRef.current);
    //         }
    //     };
    // }, [scrollingPaused]);

    // 添加鼠标事件处理函数
    const handleMouseEnter = () => {
        setScrollingPaused(true);
    };

    const handleMouseLeave = () => {
        setScrollingPaused(false);
    };

    useEffect(() => {
        // 复制当前ref到局部变量
        const currentRef = tableBodyRef.current;

        // 在组件挂载后，为表格body添加鼠标事件
        const addMouseEvents = () => {
            const tableBody = currentRef?.querySelector('.ant-table-body');
            if (tableBody) {
                tableBody.addEventListener('mouseenter', handleMouseEnter);
                tableBody.addEventListener('mouseleave', handleMouseLeave);
            }
        };

        // 组件挂载后和数据更新后尝试添加事件
        const timer = setTimeout(addMouseEvents, 100);

        return () => {
            clearTimeout(timer);
            // 清理事件监听，使用之前保存的局部变量
            const tableBody = currentRef?.querySelector('.ant-table-body');
            if (tableBody) {
                tableBody.removeEventListener('mouseenter', handleMouseEnter);
                tableBody.removeEventListener('mouseleave', handleMouseLeave);
            }
        };
    }, [datas]);

    return <BlockPanel bodyClassName={"layout-v"} className="fill layout-v h0" title={<div>
        {title}（<span>{datas?.length}</span>）
    </div>} bodyStyle={{
        overflow: 'hidden'
    }}>
        <div ref={tableBodyRef} className="table-div fill h0">
            <ScrollTable
                otherHeight={80}
                parentNode={tableBodyRef}
                columns={[{
                    title: '站点名',
                    dataIndex: 'zdm',
                    ellipsis: true
                }, {
                    title: '操作',
                    width: 90,
                    align: "center",
                    render: (text, record) => {
                        return <Button icon={<SearchOutlined />} style={{
                            color: "#0BDC95"
                        }} type="link" size="small" onClick={e => {
                            props.onDetail?.(record);
                        }}>详情</Button>
                    }
                }]}
                dataSource={datas}
                size="small"
                // bordered
                pagination={{
                    current: currentPage,
                    pageSize: 5,
                    simple: true,
                    onChange: (page) => {
                        setCurrentPage(page);
                    }
                }}
            // scroll={{ y: 200 }}
            />
        </div>
    </BlockPanel>;
}